import { create } from 'zustand';

interface SocketData {
  channel: string;
  [key: string]: unknown;
}

interface SharedStore {
  // 基本状态
  socket: {
    conn: WebSocket | null;
    status: string;
  };
  showLoginDialog: boolean;
  chatListStyle: string;
  chatStream: boolean;
  
  // 操作方法
  setShowLoginDialog: (show: boolean) => void;
  setChatListStyle: (style: string) => void;
  setChatStream: (stream: boolean) => void;
  setSocket: (socket: WebSocket) => void;
  
  // 消息处理
  messageHandlers: Record<string, ((data: SocketData) => void)[]>;
  addMessageHandler: (channel: string, handler: (data: SocketData) => void) => void;
  removeMessageHandler: (channel: string) => void;
}

// 创建共享状态
export const useSharedStore = create<SharedStore>((set, get) => ({
  // 初始状态
  socket: {
    conn: null,
    status: 'disconnected'
  },
  showLoginDialog: false,
  chatListStyle: 'default',
  chatStream: true,
  messageHandlers: {},
  
  // 设置登录对话框显示状态
  setShowLoginDialog: (show: boolean) => set({ showLoginDialog: show }),
  
  // 设置聊天列表样式
  setChatListStyle: (style: string) => set({ chatListStyle: style }),
  
  // 设置聊天流模式
  setChatStream: (stream: boolean) => set({ chatStream: stream }),
  
  // 设置WebSocket连接
  setSocket: (socket: WebSocket) => set({ 
    socket: {
      conn: socket,
      status: 'connected'
    } 
  }),
  
  // 添加消息处理器
  addMessageHandler: (channel: string, handler: (data: SocketData) => void) => {
    const currentHandlers = get().messageHandlers;
    const channelHandlers = currentHandlers[channel] || [];
    
    set({
      messageHandlers: {
        ...currentHandlers,
        [channel]: [...channelHandlers, handler]
      }
    });
  },
  
  // 移除消息处理器
  removeMessageHandler: (channel: string) => {
    const currentHandlers = { ...get().messageHandlers };
    delete currentHandlers[channel];
    set({ messageHandlers: currentHandlers });
  }
}));

// 初始化WebSocket连接
export const initWebSocket = () => {
  const store = useSharedStore.getState();
  
  // 如果已经有连接，先关闭
  if (store.socket.conn) {
    store.socket.conn.close();
  }
  
  // 创建新的WebSocket连接
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const ws = new WebSocket(`${protocol}//${window.location.host}/ws`);
  
  ws.onopen = () => {
    console.log('WebSocket连接已建立');
    store.setSocket(ws);
  };
  
  ws.onmessage = (event) => {
    try {
      const data: SocketData = JSON.parse(event.data);
      const handlers = store.messageHandlers[data.channel] || [];
      
      // 调用所有注册的处理器
      handlers.forEach(handler => handler(data));
    } catch (e) {
      console.error('WebSocket消息处理错误:', e);
    }
  };
  
  ws.onclose = () => {
    console.log('WebSocket连接已关闭');
    // 尝试重新连接
    setTimeout(() => initWebSocket(), 3000);
  };
  
  ws.onerror = (error) => {
    console.error('WebSocket错误:', error);
  };
  
  return ws;
};

// 在应用初始化时调用
if (typeof window !== 'undefined') {
  initWebSocket();
} 